<?php

namespace App\Console\Commands\ChatGroup;

use App\Models\ChatGroup\ChatGroupSessionModel;
use App\Models\Common\ConfigModel;
use App\Service\ChatGroup\ChatGroupSessionService;
use App\Service\ChatGroup\ChatGroupStructService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class AutoCloseSession extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'chatGroup:auto-close-session';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动关闭会话';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $closeSessionInterval = ConfigModel::getValue('chatGroup', 'closeSessionInterval');
        ChatGroupSessionModel::query()
            ->where('lastMsgTime', '>', Carbon::now()->subHours(2)->timestamp)
            ->where('status', ChatGroupSessionModel::STATUS_OK)
            ->get()
            ->each(function (ChatGroupSessionModel $chatGroupSessionModel) use ($closeSessionInterval){
                if (($chatGroupSessionModel->lastMsgTime + $closeSessionInterval) <= Carbon::now()->timestamp) {

                    Log::info('ChatGroup:检测到未关闭的会话ID:' . $chatGroupSessionModel->id);
                    $chatGroupSessionModel->status   = ChatGroupSessionModel::STATUS_CLOSE;
                    $chatGroupSessionModel->robotIn  = ChatGroupSessionModel::ROBOT_IN_YES;
                    $chatGroupSessionModel->serveIn  = ChatGroupSessionModel::SERVE_IN_NO;
                    $chatGroupSessionModel->save();

                    Log::info('ChatGroup:会话ID:' . $chatGroupSessionModel->id . ' 已自动关闭');

                    // 会话关闭
                    ChatGroupSessionService::closeSessionChange($chatGroupSessionModel);
                }
            });
    }
}
